package com.whut.whw.find;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.whut.whw.R;
import com.whut.whw.model.Goods;
import com.whut.whw.util.ConvertUtils;

import java.text.SimpleDateFormat;
import java.util.List;

import static com.whut.whw.constant.ConfigConsts.IMG_URL;

/**
 * <pre>
 *     author : 杨丽金
 *     time   : 2017/06/22
 *     desc   : 发现页面物品列表Recycleview适配器
 *     version: 1.0
 * </pre>
 */
public class FindGoodsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    /**
     * recyclerView的点击、长按事件
     */
    public interface OnItemClickListener {
        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }


    // 数据源
    private List<Goods> datas = null;
    // context
    private Context context;
    private static final int TYPE_ITEM = 0;// item布局
    private static final int TYPE_FOOTER = 1;// 尾布局
    private OnItemClickListener mOnItemClickListener;
    // 标记数据显示是否已经到底
    private boolean footerFlag = false;

    public void setFooterFlag(boolean footerFlag) {
        this.footerFlag = footerFlag;
    }

    public boolean isFooterFlag() {
        return footerFlag;
    }

    public void setOnItemClickLitener(OnItemClickListener mOnItemClickListener) {
        this.mOnItemClickListener = mOnItemClickListener;
    }

    public FindGoodsListAdapter(Context context, List<Goods> datas) {
        this.context = context;
        this.datas = datas;
    }

    /**
     * 得到数据源
     * @return
     */
    public List<Goods> getDatas() {
        return datas;
    }

    @Override
    public int getItemViewType(int position) {
        if (position + 1 == getItemCount()) {
            return TYPE_FOOTER;
        } else {
            return TYPE_ITEM;
        }
    }

    //获取数据的数量
    @Override
    public int getItemCount() {
        return datas.size() == 0 ? 0 : datas.size() + 1;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_goods, parent,
                    false);
            return new ItemViewHolder(view);
        } else if (viewType == TYPE_FOOTER) {
            View view = LayoutInflater.from(context).inflate(R.layout.default_loading, parent,
                    false);
            return new FootViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ItemViewHolder) {
            final ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
            Goods goodsItem = datas.get(position);

            // 用户头像
            Glide.with(context).load(IMG_URL +goodsItem.getUser().getYhtx()).asBitmap()
                    .placeholder(R.mipmap.ic_launcher).error(R.drawable.girl).centerCrop()
                    .into(new SimpleTarget<Bitmap>(ConvertUtils.dp2px(42), ConvertUtils.dp2px(42)) {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    itemViewHolder.mHeadImg.setImageBitmap(resource);
                }
            });
            // 主图片
            Glide.with(context).load(IMG_URL + (goodsItem.getZp().split(";"))[0]).asBitmap()
                    .placeholder(R.mipmap.ic_launcher).error(R.drawable.girl).centerCrop()
                    .into(new SimpleTarget<Bitmap>(ConvertUtils.dp2px(300), ConvertUtils.dp2px(200)) {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    itemViewHolder.mMainImg.setImageBitmap(resource);
                }
            });
           /* String tag = (String) viewHolder.mHeadImg.getTag();
            if (!StringUtils.equals(internetUrl, tag)) {
                viewHolder.mHeadImg.setImageResource(R.mipmap.ic_launcher);
            }
            Glide.with(context).load(internetUrl).asBitmap().placeholder(R.mipmap.ic_launcher)
                    .error(R.drawable.girl).centerCrop().into(new SimpleTarget<Bitmap>
                    (ConvertUtils.dp2px(36), ConvertUtils.dp2px(36)) {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap>
                        glideAnimation) {
                    viewHolder.mHeadImg.setTag(internetUrl);
                    viewHolder.mHeadImg.setImageBitmap(resource);
                }
            });*/
           // 用户昵称
            itemViewHolder.mTvName.setText(goodsItem.getUser().getNc());
            // 时间地址
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            StringBuilder publishTimeAndAddressStr = new StringBuilder();
            publishTimeAndAddressStr.append(sdf.format(goodsItem.getFbsj()))
                    .append(" 来自:")
                    .append(goodsItem.getSzss());
            itemViewHolder.mTvPublishTimeAndAddress.setText(publishTimeAndAddressStr.toString());

            itemViewHolder.mTvPrice.setText("￥"+goodsItem.getGj()+"");
            itemViewHolder.mTvTitle.setText(goodsItem.getBt());
            itemViewHolder.mTvDescription.setText(goodsItem.getMs());
            itemViewHolder.mTvCounts.setText("点赞" + goodsItem.getDzsl() + ";评论" + goodsItem.getPlsl()+";想要" + goodsItem.getXysl());

            // 如果设置了回调，则设置点击事件
            if (mOnItemClickListener != null) {
                itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = itemViewHolder.getLayoutPosition();
                        mOnItemClickListener.onItemClick(itemViewHolder.itemView, pos);
                    }
                });
                itemViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int pos = itemViewHolder.getLayoutPosition();
                        mOnItemClickListener.onItemLongClick(itemViewHolder.itemView, pos);
                        return true;
                    }
                });
            }
        } else if (holder instanceof FootViewHolder) {
            FootViewHolder footHolder = (FootViewHolder) holder;
            if (footerFlag) {
                footHolder.loading_liearlayout.setVisibility(View.GONE);
                footHolder.loading_finished_linearlayout.setVisibility(View.VISIBLE);
            } else {
                footHolder.loading_liearlayout.setVisibility(View.VISIBLE);
                footHolder.loading_finished_linearlayout.setVisibility(View.GONE);
            }
        }
    }


    //自定义的ViewHolder，持有每个Item的的所有界面元素
    class ItemViewHolder extends RecyclerView.ViewHolder {
        // 头像
        ImageView mHeadImg;
        // 主图片
        ImageView mMainImg;
        // 用户昵称
        TextView mTvName;
        // 发布时间和发布地址
        TextView mTvPublishTimeAndAddress;
        // 估价
        TextView mTvPrice;
        // 物品标题
        TextView mTvTitle;
        // 物品描述
        TextView mTvDescription;
        // 评论数、点赞数、想要数
        TextView mTvCounts;

        public ItemViewHolder(View view) {
            super(view);

            mHeadImg = (ImageView) view.findViewById(R.id.civ_goodsItem_headImg);
            mMainImg = (ImageView) view.findViewById(R.id.iv_goodsItem_mainImg);
            mTvName = (TextView) view.findViewById(R.id.tv_goodsItem_name);
            mTvPublishTimeAndAddress = (TextView) view.findViewById(R.id.tv_goodsItem_pulishTimeAndAddress);

            mTvPrice = (TextView) view.findViewById(R.id.tv_goodsItem_price);
            mTvTitle = (TextView) view.findViewById(R.id.tv_goodsItem_title);
            mTvDescription = (TextView) view.findViewById(R.id.tv_goodsItem_description);
            mTvCounts = (TextView) view.findViewById(R.id.tv_goodsItem_counts);
        }
    }

    // 尾布局ViewHolder
    class FootViewHolder extends RecyclerView.ViewHolder {
        LinearLayout loading_finished_linearlayout;
        LinearLayout loading_liearlayout;

        public FootViewHolder(View itemView) {
            super(itemView);
            loading_finished_linearlayout = (LinearLayout) itemView.findViewById(R.id.loading_finished_linearlayout);
            loading_liearlayout = (LinearLayout) itemView.findViewById(R.id.loading_linearlayout);
        }
    }

    /**
     * 更新数据源
     * @param datas
     */
    public void updateData(List<Goods> datas) {
        this.datas = datas;
        notifyDataSetChanged();
    }

    /**
     * 向数据源中追加数据
     * @param datas
     */
    public void appendData(List<Goods> datas) {
        this.datas.addAll(datas);
        notifyDataSetChanged();
    }

    /**
     * 删除某一条目
     * @param position
     */
    public void removeData(int position) {
        datas.remove(position);
        notifyItemRemoved(position);
    }


}


